package com.lwl.leetcode;

import org.junit.Test;

/**
 * @author lwl
 * @Description 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * @date 2023/7/27 16:43
 */
public class Code14LongestCommonPrefix {

    @Test
    public void test() {
        System.out.println(longestCommonPrefix(new String[]{"aa"}));
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String longestCommonPrefix = "";
        boolean flag = false;
        for (int i = 1; i <= strs[0].length(); i++) {
            longestCommonPrefix = strs[0].substring(0, i);
            for (int j = 0; j < strs.length; j++) {
                if (!strs[j].startsWith(longestCommonPrefix)) {
                    flag = true;
                }
            }
            if (flag) {
                break;
            }
        }
        return flag ? longestCommonPrefix.substring(0, longestCommonPrefix.length() - 1) : longestCommonPrefix;
    }
}
